package pers.leo.couplepointjava.util;

import org.junit.Assert;
import org.springframework.test.web.servlet.MvcResult;

import java.io.UnsupportedEncodingException;

/**
 * MvcResult 工具类
 *
 * @author Leo
 * @since 2021/8/25
 */
public class MvcResultUtil {

    private final static int SUCCESS_STATUS = 200;

    private final static int FAIL_STATUS = 404;

    public static void verifyDataSuccess(MvcResult mvcResult, String expectedContent) {
        verifyData(mvcResult, SUCCESS_STATUS, expectedContent);
    }

    public static void verifyDataFail(MvcResult mvcResult, String expectedContent) {
        verifyData(mvcResult, FAIL_STATUS, expectedContent);
    }

    public static void verifyStatusSuccess(MvcResult mvcResult) {
        verifyStatus(mvcResult, SUCCESS_STATUS);
    }

    public static void verifyStatusFail(MvcResult mvcResult) {
        verifyStatus(mvcResult, FAIL_STATUS);
    }

    /**
     * 验证数据
     *
     * @param mvcResult       mvc 结果类
     * @param expectedStatus  预期状态值
     * @param expectedContent 预期内容
     */
    public static void verifyData(MvcResult mvcResult, int expectedStatus, String expectedContent) {
        try {
            int actualStatus = mvcResult.getResponse().getStatus();
            String actualContent = mvcResult.getResponse().getContentAsString();

            Assert.assertEquals(expectedStatus, actualStatus);
            Assert.assertEquals(expectedContent, actualContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证状态
     *
     * @param mvcResult      mvc 结果类
     * @param expectedStatus 预期状态值
     */
    public static void verifyStatus(MvcResult mvcResult, int expectedStatus) {
        try {
            int actualStatus = mvcResult.getResponse().getStatus();

            Assert.assertEquals(expectedStatus, actualStatus);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void printContent(MvcResult mvcResult) throws UnsupportedEncodingException {
        String content = mvcResult.getResponse().getContentAsString();
        System.out.println(content);
    }

    private MvcResultUtil() {
    }

}
